package models

import (
	"encoding/json"
	"fmt"
	"heyzhima-yt-cpu/pkg/logging"
	"github.com/jinzhu/gorm"
)


type CpuCards struct {
	//gorm.Model
	ID            int    `gorm:"primary_key" json:"id"`
	CardCode      string `json:"card_code"`
	CardSecret    string `json:"card_secret"`
	ZoneId       int `json:"zone_id"`
	CreatedAt     int64 `json:"created_at"`
	UpdatedAt     int64 `json:"updated_at"`
	DeletedAt     int64 `json:"deleted_at"`
}

type  Res struct{
UserName string  `gorm:"column:user_name"`
UserMobile string  `gorm:"column:user_mobile"`
BuildingNamePath string  `gorm:"column:building_name_path"`
CardId         int            `gorm:"primary_key" json:"card_id"`
Uid            string         `json:"uid"`
CardCode       string         `json:"card_code"`
CardNum        string         `json:"card_num"`
CardExpired    int64            `json:"card_expired"`
CardType       string `json:"card_type"`
CardFunc       string `json:"card_func"`
CardDisabled   string `json:"card_disabled"`
CardDesc       string `json:"card_desc"`
CardScan       string `json:"card_scan"`
ZoneId         int            `json:"zone_id"`
BuildingId     int  `json:"building_id"`
UserId         int64  `json:"user_id"`
RoomId         int64  `json:"room_id"`
AgentAccountId int64  `json:"agent_account_id"`
AccountId      int64  `json:"account_id"`
LastUse        int64  `json:"last_use"`
CreatedAt      int64  `json:"created_at"`
UpdatedAt      int64  `json:"updated_at"`
DeletedAt      int64  `json:"deleted_at"`
}


type ExistCpuCards struct {
	Id        int
}
// ExistArticleByID checks if an article exists based on ID
func ExistCpuCardsByID(card_code string) (bool, error) {
	var cpu_cards ExistCpuCards
	//err := db.Select("id").Where("card_code = ? ", card_code).First(&cpu_cards).Error
	err := db.Table("ims_cpu_cards").Select("id").Where("card_code = ?", card_code).First(&cpu_cards).Error
	//db.Select(id).Find(&cpu_cards)
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	fmt.Println(cpu_cards)
	if cpu_cards.Id > 0 {
		return true, nil
	}
	return false, nil
}

//获取卡信息
func CpuCardsByCode(card_code string) (string, error) {
	var cpu_cards CpuCards
	err := db.Select("card_secret").Where("card_code = ? ", card_code).First(&cpu_cards).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return cpu_cards.CardSecret, err
	}
	return cpu_cards.CardSecret, nil
}


//后台门卡信息
func GetCpuCardsInfo(code string,zoneId int) ([]*Res, error) {
	var result []*Res
	err:=db.Table("ims_cards").Select("user_name,user_mobile,building_name_path,ims_cards.*").
		Joins("left join ims_users on ims_cards.user_id=ims_users.user_id").
		Joins("left join ims_buildings on ims_buildings.building_id=ims_cards.building_id").
		Where("card_code=? and ims_cards.zone_id=? and card_disabled=?",code,zoneId,"N").
		Order("card_id DESC").
		Scan(&result).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	fmt.Printf("%v", mapToJson(result))
	logging.Info(result)
	return result, nil
}

func mapToJson(result interface{}) string {
	// map转 json str
	jsonBytes, _ := json.Marshal(result)
	jsonStr := string(jsonBytes)
	return jsonStr
}

func Update(code string,secret string)(bool,error){
	var cpu_cards CpuCards
	result :=db.Model(&cpu_cards).Where("card_code = ?", code).Update("card_secret", secret)
	if result.RowsAffected>0{
		return true,nil
	}else{
		return false,result.Error
	}

}

// AddCpuCards add a single cpu card
func AddCpuCards(data map[string]interface{}) error {
	cpu_cards := CpuCards{
		ID:         data["id"].(int),
		CardCode:         data["card_code"].(string),
		CardSecret:          data["card_secret"].(string),
		ZoneId:       data["zone_id"].(int),
	}
	if err := db.Create(&cpu_cards).Error; err != nil {
		return err
	}

	return nil
}
